import { defineStore } from "pinia";
import { ref } from "vue";
import { message } from "ant-design-vue";
import {
  bingInviterCode,
  checkShareLink,
  getUserDetail
} from "../docsapi/user";
import { getCookie, deleteCookie } from "../common/tools";
let lodinCb = new Map(); // 存储登录回调函数
export const useUserStore = defineStore("userStore", () => {
  const token = ref("");
  const userInfo = ref({});
  const loginStatus = ref(false);
  const openLoginModal = ref(false);
  const getuserInfoLoding = ref(false);
  const os = ref("");
  const setOpenLoginModal = value => {
    openLoginModal.value = value;
  };
  const setToken = newToken => {
    token.value = newToken;
    getuserInfo();
    localStorage.setItem("token", newToken);
  };
  const getuserInfo = async () => {
    getuserInfoLoding.value = true;
    getUserDetail()
      .then(data => {
        if (!data.code) {
          userInfo.value = data.data;
          loginStatus.value = true;
          if (!data.data.invite_code) {
            bingInviterCodeFun();
          }
          const cb = lodinCb.get("isShareLink");
          cb && cb();
          setOpenLoginModal(false);
        } else {
          message.error(data.error || "Failed to fetch user info");
        }
      })
      .catch(error => {
        console.error("Error fetching user info:", error);
      })
      .finally(() => {
        getuserInfoLoding.value = false;
      });
  };
  const logout = () => {
    token.value = "";
    userInfo.value = {};
    loginStatus.value = false;
    localStorage.removeItem("token");
    message.success("退出登陆成功");
  };

  const initLoginUserInfo = () => {
    const storedToken = localStorage.getItem("token");
    if (storedToken) {
      setToken(storedToken);
    } else {
      token.value = "";
      userInfo.value = {};
      loginStatus.value = false;
    }
  };

  const bingInviterCodeFun = async () => {
    const share_link_id = getCookie("share_link_id");
    if (!share_link_id) {
      return;
    }
    const cheack = await checkShareLink({
      id: share_link_id
    });
    if (!cheack.data) {
      console.log("分享链接不可用");

      document.cookie =
        "share_link_id=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
      return;
    } // 如果没有登录并且有分享链接
    bingInviterCode({ invite_code: share_link_id }).then(res => {
      console.log("bind_invite_code res:", res);
    });
  };

  const initGetSysOs = () => {
    // 获取系统信息
    const ua = navigator.userAgent.toLowerCase();
    if (ua.indexOf("android") > -1) {
      os.value = "android";
    }
    if (ua.indexOf("iphone") > -1 || ua.indexOf("ipad") > -1) {
      os.value = "ios";
    }
    if (ua.indexOf("mac") > -1) {
      os.value = "mac";
    }
    if (ua.indexOf("windows") > -1) {
      os.value = "windows";
    }
    if (ua.indexOf("linux") > -1) {
      os.value = "linux";
    }
    console.log("os:", os.value);
  };

  // 判断是不是分享链接进来的并且邀请码是否可用
  async function isShareLink(cb) {
    lodinCb.set("isShareLink", cb);
    const share_link_id = getCookie("share_link_id");
    if (!loginStatus.value && share_link_id) {
      const cheack = await checkShareLink({
        id: share_link_id
      });
      if (!cheack.data) {
        message.error("分享链接不可用");

        document.cookie =
          "share_link_id=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
        return;
      }
      setOpenLoginModal(true);
      return;
    }
    cb && cb() && lodinCb.delete("isShareLink");
  }

  return {
    token,
    setToken,
    getuserInfo,
    userInfo,
    loginStatus,
    openLoginModal,
    setOpenLoginModal,
    logout,
    initLoginUserInfo,
    getuserInfoLoding,
    bingInviterCodeFun,
    isShareLink,
    initGetSysOs,
    os
  };
});
